package com.jxj.study.allConfig.redisConfig;

import com.jxj.study.util.ApplicationContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.cache.Cache;
import org.springframework.data.redis.core.RedisTemplate;

import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/*
    https://blog.csdn.net/shaoming314/article/details/109153487
* redis作为mybatis二级缓存的配置
*/
@Slf4j
public class RedisCache implements Cache {

    private String id;

    private final ReadWriteLock readWriteLock = new ReentrantReadWriteLock();

    public RedisCache(String id) {
        log.info("当前的缓存id: [{}]",id);
        this.id = id;
    }

    @Override
    public String getId() {
        return this.id;
    }

    @Override//放入redis缓存
    public void putObject(Object key, Object value) {
        log.info("放入缓存key:[{}] 放入缓存的value:[{}]",key,value);
        getRedisTemplate().opsForHash().put(id,key.toString(),value);
    }

    @Override//从redis缓存获取
    public Object getObject(Object key) {
        log.info("获取缓存的key:[{}]",key.toString());
        return getRedisTemplate().opsForHash().get(id,key.toString());
    }

    @Override//删除指定缓存信息
    public Object removeObject(Object key) {
        return getRedisTemplate().boundHashOps(getId()).delete(key);
    }

    @Override//清除缓存
    public void clear() {
        log.info("清除所有缓存信息...");
        getRedisTemplate().delete(getId());
    }

    @Override
    public int getSize() {
        return getRedisTemplate().opsForHash().size(id).intValue();
    }

    @Override
    public ReadWriteLock getReadWriteLock() {
        return readWriteLock;
    }

    //封装获取redistemplate的方法
    public RedisTemplate<String,String> getRedisTemplate(){
        return ApplicationContextUtils.getBean("redisTemplate");
    }

}